
//数据加载错误面页
const ChartAreaErrorLayer = $('#ChartAreaErrorLayer')[0].innerHTML;


var Chart = (function(){
    let colormap = {
        normal: '#009688',
        abnormal: ['#5b5c5e', '#575759']
    };
    const ChartAreaNoDataLayer = $('#ChartAreaNoDataLayer')[0].innerHTML;


    return {
        /**
         * @param dom
         * @param {{Object}} data={
              completeRate: 20%, 完成度(用于显示在图标中间)
               data:[
                 {value:400, name:'已经拥有'}, //第一条为正常数据
                 {value:200, name:'4月'},
                {value:200, name:'4月'},
             ]}
         */
        init: function (dom, setting) {
            if(!setting){
                //没有数据
                $(dom).children().remove();
                $(dom).html(ChartAreaNoDataLayer);
                return;
            }
            $(dom).removeAttr('_echarts_instance_').children().remove(); //FIXME 第二次渲染会造成无效果

            // $(dom).html('');

            let chart = echarts.init(dom);

            let data = setting.data;

            //标签
            let label = {
                show: true,
                position: 'inner',
            };

            //生成颜色表
            let color = [];
            color.push(colormap.normal);
            let j = 0;
            for(let i=1; i < data.length; i++){
                color.push(colormap.abnormal[j]);
                j = ++j % colormap.abnormal.length;
                data[i].label = label;
            }
            // console.log(data);

            chart.setOption({
                // animation:false,
                graphic: {
                    type: 'text',
                    left: 'center',
                    top: 'center',
                    style: {
                        text: setting.completeRate || '',
                        textAlign: 'center',
                        fill: '#01601b',
                        width: 42,
                        height: 42,
                        textStyle: 'bold'
                    }
                },
                series : [
                    {
                        // name: '访问来源',
                        type: 'pie',
                        radius: ['30%', '60%'],  // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
                        color: color,
                        data: data,
                        itemStyle: {
                            normal: {
                                // shadowBlur: 200,
                                // shadowColor: 'rgba(0, 0, 0, 0.5)',
                                label: {
                                    show: true,
                                    position: 'outer',

                                }
                            }
                        }
                    }
                ]
            })
            return chart;
        }
    }


})();


/**
 * 读取面页绘图区域
 * {
 *     1:{
 *         '一类': dom,
 *         '二类': dom,
 *         ...
 *     },
 *     2: {
 *         ...
 *     }
 * }
 */
let CharArea = (function(){
    let area = {};
    let jqs = $('div.layui-container>.layui-row');
    for(let i =0; i< jqs.length; i++){
        // Chart.init(jqs[i], data);
        let report = jqs.eq(i).data().report;
        if(!report){continue;}
        area[report] = {};
        let charts = jqs.eq(i).find('div.layui-card>.chart-area');
        for(let j=0; j < charts.length; j++){
            let value;
            value = charts.eq(j).data().idv || charts.eq(j).data().type;
            if(value){
                area[report][value] = charts[j];
            }else{
                area[report] = charts[j];
            }
        }
    }
    // console.log('chartArea', area);
    return area;
})();



$(function () {
    layui.use(['jquery', 'form', 'laytpl', 'laydate', 'element', 'layer'], function () {
        var $ = layui.jquery, form = layui.form, laydate = layui.laydate, element = layui.element, layer=layui.layer;

        const IdvClass = ['一类', '二类', '特殊', '帮困'];

        //渲染数据
        let renderChart = function(reportId, data, year){
            let chartData = {};
            for(let i in data){
                let each = data[i];
                if(! (each.class in chartData)){ chartData[each.class] = {}}
                let month = parseInt(each.month);
                chartData[each.class][month] = each.num;
            }
            // console.log('chartData', chartData);
            // return;

            const thisMonth = new Date().getMonth();
            const thisYear = new Date().getFullYear();
            let month = year==thisYear?thisMonth:12;
            /**
             * 由已经存在的月份数据计算出不存在的月份数据
             * @param list
             * @return {Object}
             */
            let generate = function(list){
                let lost = [];
                for(let i =1; i<= month; i++){
                    if(!(i in list)){
                        lost.push(i);
                    }
                }
                // console.log(list);
                return lost;
            };

            //格式化为chart数据
            for(let clazz in chartData){
                let data = [];
                let list = generate(chartData[clazz]);
                data.push({name: '已导入', value: Object.keys(chartData[clazz]).length});
                for(let i in list){
                    data.push({
                        name: list[i],
                        value: 1
                    })
                }
                chartData[clazz] = {
                    data: data,
                    completeRate: parseInt((data[0].value / 12) * 100) + '%'
                };
            }
            // console.log('chartData', chartData);
            //渲染图表
            for(let i in IdvClass){
                let clazz = IdvClass[i];
                // console.log('渲染', clazz, reportId);
                Chart.init(CharArea[reportId][clazz], chartData[clazz]);
            }


        };

        let failedUpdateData = function(reportId){
            let area = CharArea[reportId];
            if(! area){return;}
            for(let i in area){
                $(area[i]).html(ChartAreaErrorLayer);
            }
        };

        //请求数据分布
        let updateData = function(year){
            const reportId = [1, 2, 3];
            let p = 0;

            let fetch = function () {
                if(p >= reportId.length){
                    window.resizeWindowHeight?window.resizeWindowHeight():'';
                    return;
                }
                let report = reportId[p];

                $.ajax({
                    type: 'POST',
                    url: 'selectDistribution',
                    data: {reportId: report, year: year},
                    success: function (res) {
                        if(res && res.code == ERROR_CODE.SUCCESS){
                            renderChart(report, res.data, year);
                        }else{
                            failedUpdateData(report);
                        }
                    },
                    error: function () {
                        failedUpdateData(report);
                    },
                    complete: function () {
                        p++;
                        fetch();
                    }

                });
            };

            fetch();

        };


        //渲染表单
        let thisYear = new Date().getFullYear();
        //日期
        // $('#filter-form-date').hide();

        form.render(null, 'filter-form');
        //初始化表单数据
        let defaultFormData = {
            year: new Date().getFullYear()
        };


        //日期(选择日期后直接更新)
        const NOW_DATE = new Date();
        const NOW = [NOW_DATE.getFullYear(), NOW_DATE.getMonth(), NOW_DATE.getDate()].join('-');
        laydate.render({
            elem: '#queryDate',
            type: 'year',
            value: defaultFormData.year,
            format: 'yyyy',
            isInitValue: true,
            min: '2018-1-1',
            max: NOW,
            theme: 'grid',
            done: function(value){
                updateData(value);
            }
        });

        updateData(thisYear);


        //更新报表按钮点击
        lay('#updateReportButton').on('click', function () {
            // console.log('打开2');
            // $('#queryUpdateDate').removeClass('layui-hide');

            laydate.render({
                elem: '#queryUpdateDate',
                show: true,
                closeStop: '#updateReportButton',
                type: 'month',
                position: 'fixed',
                value: [[NOW_DATE.getFullYear(), NOW_DATE.getMonth()].join('-'), [NOW_DATE.getFullYear(), NOW_DATE.getMonth()].join('-')],
                format: 'yyyy-MM',
                isInitValue: true,
                min: '2018-1-1',
                max: NOW,
                // range: true,
                theme: 'grid',
                done:  function(value, date){
                    // console.log(value); //得到日期生成的值，如：2017-08-18
                    if(!date.year){
                        return;
                    }

                    let loadingLayer = layer.load(2);
                    $.ajax({
                        type: 'POST',
                        url: 'updateReport',
                        data: {year:date.year, month: date.month},
                        success: function (res) {
                            if(res.code == 0){
                                layer.msg('成功', {icon: 1});
                            }else{
                                layer.msg(res.code + (res.msg || ''), {icon: 5});
                            }
                        },
                        error: function (res) {
                            layer.msg(res.status || '发生了错误', {icon: 2});
                        },
                        complete: function () {
                            layer.close(loadingLayer);
                        }
                    })
                }
            });


        });
    })
});